package com.example.competionmanagebackend.config;

import com.example.competionmanagebackend.utils.JwtUtil;
import com.example.competionmanagebackend.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class TokenInterceptor implements HandlerInterceptor {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access-token");

        if (token == null || token.trim().isEmpty()) {
            writeJson(response, new Result<>(401, "Token is missing", null));
            return false;
        }

        try {
            Claims claims = JwtUtil.parseToken(token);
            if (claims.getExpiration().before(new Date())) {
                writeJson(response, new Result<>(401, "Token has expired", null));
                return false;
            }
            // 从 token 中提取 username 并设置到 request 属性中
            String username = claims.getSubject(); // 假设 username 存储在 token 的 subject 中
            request.setAttribute("username", username);
        } catch (Exception e) {
            writeJson(response, new Result<>(401, "Invalid token: " + e.getMessage(), null));
            return false;
        }

        return true;
    }

    private void writeJson(HttpServletResponse response, Result<?> result) throws Exception {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        String json = objectMapper.writeValueAsString(result);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(json);
            writer.flush();
        }
    }
}